package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import model.ByNameModel;
import model.Contact;
import model.ContactListModel;
import view.ContactWindow;
import view.MainWindow;

/**
 * Controller which leads to the selection of the contact with the name entered by the user in the field
 * @author Marie Morin
 *
 */

public class ByNameController implements ActionListener{
	
	private MainWindow w;
	private ContactWindow a;
	private String text;	
	private ByNameModel m;
	private ArrayList<Contact> contactsList = new ArrayList<Contact>();
	
	public ByNameController(MainWindow w, ContactWindow a){
		
		this.w = w;
		this.a=a;
		this.text = "";
		
		// Create a list with all the contacts of the file 
		ContactListModel c = new ContactListModel();	
		contactsList = c.getContactsList();
	
	
	}
	
	public ByNameController(MainWindow w, String text){
		
		System.out.println("ByNameController");
		this.w = w;
		this.text=text;	

		// Create a list with all the contacts of the file 
		ContactListModel c = new ContactListModel();	
		contactsList = c.getContactsList();
		
		
		this.setListByName();
	
	}


	public ArrayList<Contact> getContactsList() {
		return contactsList;
	}

	public void setContactsList(ArrayList<Contact> contactsList) {
		this.contactsList = contactsList;
	}

	/**
	 * Function called when the user do a search by name 
	 * Call the model which actualize the display of the contact list according 
	 * to the choice of the user.
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
	
		this.text = a.getSearch();

		 m = new ByNameModel(this);		 
			
		 
		/* Set the variables StaticSearch and StaticWord with the value name and the value of 
		 * the variable text to display the right list according to the choice of the user
		 * The variable StaticWord save the string the user typed for the search.
		 * The variable StaticSearch save the type of search (by name, group, etc...).
		 */		 
		w.setStaticSearch("name");
		w.setStaticWord(text);
			
		
		if (contactsList.size()==0)
		{
			w.setLayoutNull();
		}
		else
		{
			w.setLayoutByGroup(this.contactsList);
		}	

		
	}
	
	/**
	 * Call the functions to actualize the display of the contact list
	 * 
	 * If the list the contact is empty, the window is initialize with the default parameters, if not,
	 * a specialize window with only the contact selected by the user is displayed.
	 */
	public void setListByName() {
		// TODO Auto-generated method stub

		m = new ByNameModel(this);

		if (contactsList.size()==0)
		{
			w.setLayoutNull();
		}
		else
		{
			w.setLayoutByGroup(this.contactsList);
		}
		
		
		
	}
	


	public String getText() {
		return text;
	}


	public void setText(String text) {
		this.text = text;
	}

}

